package cn.ycc1.boot3video.video;

import lombok.Data;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class MasterPlaylistGenerator {

    @Data
    // 内部静态类，确保方法可访问
    public static class VariantStream {
        // 必须添加getter方法
        private String uri;
        private int bandwidth;
        private String resolution;
        private String codecs;
        private String name;

        public VariantStream(String uri, int bandwidth, String resolution, String codecs, String name) {
            this.uri = uri;
            this.bandwidth = bandwidth;
            this.resolution = resolution;
            this.codecs = codecs;
            this.name = name;
        }

    }

    /**
     * 生成主播放列表内容（修正版本）
     */
    public static String generateMasterPlaylist(List<VariantStream> variants) {
        StringBuilder m3u8 = new StringBuilder();

        // M3U8 头部
        m3u8.append("#EXTM3U\n");
        m3u8.append("#EXT-X-VERSION:3\n");
        m3u8.append("\n");

        // 修正：使用正确的getter方法进行排序
        variants.sort((v1, v2) -> Integer.compare(v2.getBandwidth(), v1.getBandwidth()));

        // 添加每个变体流
        for (VariantStream variant : variants) {
            m3u8.append("#EXT-X-STREAM-INF:");
            m3u8.append("BANDWIDTH=").append(variant.getBandwidth());

            if (variant.getResolution() != null && !variant.getResolution().isEmpty()) {
                m3u8.append(",RESOLUTION=").append(variant.getResolution());
            }

            if (variant.getCodecs() != null && !variant.getCodecs().isEmpty()) {
                m3u8.append(",CODECS=\"").append(variant.getCodecs()).append("\"");
            }

            if (variant.getName() != null && !variant.getName().isEmpty()) {
                m3u8.append(",NAME=\"").append(variant.getName()).append("\"");
            }

            m3u8.append("\n");
            m3u8.append(variant.getUri()).append("\n");
            m3u8.append("\n");
        }

        return m3u8.toString();
    }

    /**
     * 保存主播放列表到文件
     */
    public static void saveMasterPlaylistToFile(String content, String filePath) throws IOException {
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(content);
            System.out.println("Master playlist saved to: " + filePath);
        }
    }

    /**
     * 生成支持切换清晰度的主播放列表
     */
    public static void generateSwitchableMasterPlaylist(String outputDir) {
        // 创建不同清晰度的变体流配置
        List<VariantStream> variants = new ArrayList<>();

        variants.add(new VariantStream(
                "1080p.m3u8",
                2000000,
                "1920x1080",
                "avc1.640028,mp4a.40.2",
                "超清"
        ));

        variants.add(new VariantStream(
                "720p.m3u8",
                1000000,
                "1280x720",
                "avc1.64001f,mp4a.40.2",
                "高清"
        ));

        variants.add(new VariantStream(
                "480p.m3u8",
                500000,
                "854x480",
                "avc1.64001e,mp4a.40.2",
                "标清"
        ));

        variants.add(new VariantStream(
                "360p.m3u8",
                250000,
                "640x360",
                "avc1.64001e,mp4a.40.2",
                "流畅"
        ));

        // 生成主播放列表内容
        String masterContent = generateMasterPlaylist(variants);

        // 保存到文件
        try {
            String masterFilePath = outputDir + "/master.m3u8";
            saveMasterPlaylistToFile(masterContent, masterFilePath);
            System.out.println("支持切换清晰度的主播放列表已生成！");
        } catch (IOException e) {
            System.err.println("Failed to save master playlist: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 动态生成主播放列表（根据实际存在的文件）
     */
    public static void generateDynamicMasterPlaylist(String outputDir) {
        List<VariantStream> variants = new ArrayList<>();

        // 检查哪些清晰度文件实际存在
        String[] qualities = {"1080p", "720p", "480p", "360p"};
        java.io.File outputFolder = new java.io.File(outputDir);

        for (String quality : qualities) {
            String playlistFile = quality + ".m3u8";
            java.io.File file = new java.io.File(outputFolder, playlistFile);

            if (file.exists()) {
                // 根据清晰度设置参数
                VariantStream variant = createVariantForQuality(quality, playlistFile);
                if (variant != null) {
                    variants.add(variant);
                    System.out.println("包含清晰度: " + quality);
                }
            } else {
                System.out.println("跳过不存在的清晰度: " + quality);
            }
        }

        if (variants.isEmpty()) {
            System.err.println("在目录中没有找到任何清晰度文件: " + outputDir);
            return;
        }

        // 生成并保存主播放列表
        String masterContent = generateMasterPlaylist(variants);
        try {
            String masterFilePath = outputDir + "/master.m3u8";
            saveMasterPlaylistToFile(masterContent, masterFilePath);
            System.out.println("动态主播放列表已生成，包含 " + variants.size() + " 个清晰度");
        } catch (IOException e) {
            System.err.println("保存主播放列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据清晰度创建对应的变体流配置
     */
    private static VariantStream createVariantForQuality(String quality, String playlistFile) {
        switch (quality) {
            case "1080p":
                return new VariantStream(playlistFile, 2000000, "1920x1080", "avc1.640028,mp4a.40.2", "超清");
            case "720p":
                return new VariantStream(playlistFile, 1000000, "1280x720", "avc1.64001f,mp4a.40.2", "高清");
            case "480p":
                return new VariantStream(playlistFile, 500000, "854x480", "avc1.64001e,mp4a.40.2", "标清");
            case "360p":
                return new VariantStream(playlistFile, 250000, "640x360", "avc1.64001e,mp4a.40.2", "流畅");
            default:
                return null;
        }
    }

    /**
     * 简化的生成方法（如果之前的方法太复杂）
     */
    public static void simpleGenerateMasterPlaylist(String outputDir) {
        // 直接构建内容，不使用排序
        StringBuilder m3u8 = new StringBuilder();
        m3u8.append("#EXTM3U\n");
        m3u8.append("#EXT-X-VERSION:3\n\n");

        // 按带宽从高到低手动排序
        m3u8.append("#EXT-X-STREAM-INF:BANDWIDTH=2000000,RESOLUTION=1920x1080,CODECS=\"avc1.640028,mp4a.40.2\",NAME=\"超清\"\n");
        m3u8.append("1080p.m3u8\n\n");

        m3u8.append("#EXT-X-STREAM-INF:BANDWIDTH=1000000,RESOLUTION=1280x720,CODECS=\"avc1.64001f,mp4a.40.2\",NAME=\"高清\"\n");
        m3u8.append("720p.m3u8\n\n");

        m3u8.append("#EXT-X-STREAM-INF:BANDWIDTH=500000,RESOLUTION=854x480,CODECS=\"avc1.64001e,mp4a.40.2\",NAME=\"标清\"\n");
        m3u8.append("480p.m3u8\n\n");

        m3u8.append("#EXT-X-STREAM-INF:BANDWIDTH=250000,RESOLUTION=640x360,CODECS=\"avc1.64001e,mp4a.40.2\",NAME=\"流畅\"\n");
        m3u8.append("360p.m3u8\n");

        try {
            saveMasterPlaylistToFile(m3u8.toString(), outputDir + "/master.m3u8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        String outputDir = "/tmp/hls_output";

        // 测试1: 生成支持切换的主播放列表
        System.out.println("=== 测试1: 生成支持切换的主播放列表 ===");
        generateSwitchableMasterPlaylist(outputDir);

        // 测试2: 动态生成
        System.out.println("\n=== 测试2: 动态生成主播放列表 ===");
        generateDynamicMasterPlaylist(outputDir);

        // 测试3: 简化生成
        System.out.println("\n=== 测试3: 简化生成主播放列表 ===");
        simpleGenerateMasterPlaylist(outputDir);
    }
}
